var PrivaliaCoreUI = new Class.create({
    initialize: function () {
	this.debug = 
true;
        this.errId = '82';
        this.error = false;
        this.i_segTimeout = 15;
        this.timeout = null;
        this.txt_msgError = 'Unable to load the page properly. Try again in a few minutes';
        this.url_400 = URL_DOMAIN + '/error/e400';
        this.url_408 = URL_DOMAIN + '/error/e408';
        this.url_500 = URL_DOMAIN + '/error/e500';
        this.b_timeout = false;
        this.o_versions = $H();
        this.duration_hide = 0.2;
        this.duration_show = 0.3;
        this.idLoadText = 'loading';
        this.idNotification = 'notification';
        this.idPage = 'page';
        this.loading = false;
        this.loadingTarget = '';
        this.loadingText = true;
        this.sah_hide = '';
        this.sah_show = '';
        this.sah_sufix = '_data';
        this.closeAfterSubmit = false;
        this.b_scrollToNotify = false;
        this.showLoad = true;
	this.v_txt =				[];					// array para guardar traducciones de texto

        
    },
	errorMessage:function(errorCode){

	console.log('errorMessage@'+errorCode);

	},
	    isLogged: function () {
        var code = this.getResTextcodes();
        var codeNotLogged = "msg0100403";
        var loggedIn = true;
        if (code == codeNotLogged) {
            loggedIn = false;
        }
        return loggedIn;
    },
	/**
	 * Comprueba si se esta accediendo a la web mediante un dispositivo diferente a un ordenador
	 */
	checkUserAgent: function(agent) {
		// recogemos y pasamos el useragent a minusculas para evitar el key sensitive
		var s_agent = navigator.userAgent.toLowerCase();

		// busca el useragent, si es diferente de -1 es que existe sino no existe
		// indexOf por defecto devuelve la posicion que ocupa la palabra en la string que la contiene si coincide el useragent
		if(s_agent.indexOf(agent)!= -1){
			return s_agent;
		}
   	 },
	/**
	 * Metodo que transforma segundos en dias, horas, minutos y segundos
	 * @param {Object} seconds - input de segundos
	 * @param {Object} daysRequired - 0 para resultado sin dias, 1 para resultado con dias
	 */
	getExpiresTime: function(seconds, daysAndHoursRequired){
		var timeInDays = '',
		numdays = Math.floor(seconds / 86400), // Dias
		numhours = 0,
		numminutes = 0,
		numseconds = ((seconds % 86400) % 3600) % 60; // Segundos

		// Horas
		if(Math.floor((seconds % 86400) / 3600) < 10){
			numhours = "0" + Math.floor((seconds % 86400) / 3600);
		}else{
			numhours = Math.floor((seconds % 86400) / 3600);
		};
		// Minutos
		if(Math.floor(((seconds % 86400) % 3600) / 60) < 10 ){
			numminutes = "0" + Math.floor(((seconds % 86400) % 3600) / 60);
		}else{
			numminutes = Math.floor(((seconds % 86400) % 3600) / 60);
		}

		// Volcado, diferenciando si se requieren dias y horas
		if (daysAndHoursRequired == 1){
			if (numdays == 1){
				timeInDays += numdays + ' ' + this.getTxt('day') + ', ' + numhours + this.getTxt('h');
			}else if(numdays != 0){
				timeInDays += numdays + ' ' + this.getTxt('days')+', ' + numhours + this.getTxt('h');
			}else{
				timeInDays += numhours + this.getTxt('h');
			}
			return	timeInDays += ' ' + numminutes + this.getTxt('min');
		}else{
		return	timeInDays +=  numminutes +":"+ numseconds;
		}
	},
	/**
	 * Definir y guardar la traduccion de un texto
	 */
	setTxt: function(text, translation) {
		this.v_txt[text] = translation;
	},
	/**
	 * Obtener traduccion de un texto
	 */
	getTxt: function(text) {
		return this.v_txt[text];
	},
     startTimeout: function () {
        if (this.b_timeout) {
            var seconds = this.i_segTimeout;
            this.timeout = window.setTimeout((function () {
                this.header(408);
            }).bind(this), seconds * 1000);
        }
    },
    stopTimeout: function () {
        if (this.b_timeout) {
            window.clearTimeout(this.timeout);
            if (this.debug) {}
        }
    },
    setSecondsTimeout: function (i_sec) {
        this.i_segTimeout = i_sec;
    },
    closeForm: function () {
        if (this.closeAfterSubmit) {
            this.showAndHide();
        }
    },
    closeNotify: function () {
        if (!$(this.idNotification).empty()) {
            this.hideItem(this.idNotification);
        }
    },
    hideAllData: function (id) {
        $$("#" + id + " .accordion-content").each(function (item) {
            $(item).slideUp({
                duration: 0.3
            });
        });
        $$("#" + id + " .important6").each(function (item) {
            $(item).removeClassName('open important6');
            $(item).addClassName('important3');
        });
    },
    hideItem: function (div) {
        $(div).slideUp({
            duration: this.duration_hide
        });
    },
    getMsgCode: function (err) {
        return MSGCODE[err];
    },
    load: function (target) {
	
        if (this.showLoad) {
            if (Object.isUndefined(target)) {
                target = 'page';
            }
	if(this.debug) console.log("Loading: "+target);
            if (!this.loading) {
                this.loadingTarget = target;
                if (!Prototype.Browser.IE) {
                    $(this.loadingTarget).startWaiting();
                }
                this.loading = true;
            }
        }
    },
    loadText: function (txt) {
        if (this.loadingText) {
            if (!txt) {
                txt = "loading";
            }
            try {
                $(this.idLoadText).update(txt + "...");
                $(this.idLoadText).show();
            } catch (e) {
                if (this.debug) {
                    console.log('PrivaliaCoreUI.loadText (' + this.errId + '): ', e);
                }
            }
        }
    },
    
    setShowLoad: function (showLoad) {
        this.showLoad = showLoad;
    },
    setNotification: function (id) {
        this.idNotification = id;
    },
    showAllData: function (id) {
        $$("#" + id + " .accordion-content").each(function (item) {
            $(item).slideDown({
                duration: 0.3
            });
        });
        $$("#" + id + " .important3").each(function (item) {
            $(item).className = 'important3 open important6';
        });
    },
   
    stopLoad: function () {
        if (this.loading) {
            $(this.loadingTarget).stopWaiting();
            this.loading = false;
            this.loadingTarget = '';
        }
    },
    stopLoadText: function () {
        try {
            $(this.idLoadText).fade({
                duration: 0.5
            });
        } catch (e) {
            if (this.debug) {
                alert('PrivaliaCoreUI.stopLoadText (' + this.errId + '): ', e);
            }
        }
    }
});


var PrivaliaCoreJson = Class.create(PrivaliaCoreUI, {
    initialize: function ($super) {
        $super();
        this.b_testResponse = false;
        this.build = '';
        this.built = '';
        this.cssJson = 'json';
        this.cssJsoned = 'jsoned';
        this.errId = '82';
        this.idProcess = '';
        this.numTargets = 0;
        this.reloading = false;
        this.res_data = '';
        this.res_textcodes = '';
        this.res_status = '';
        this.res_webanalytics = '';
        this.tpl = '';
        this.target = '';
        this.url_getData = '';
        this.vData = [];
        this.b_trackSite = "";
        this.reloadData = true;
        this.version = 4.0;
        
	
    },
    addBuilt: function (dataJson) {
        this.built += this.tpl.evaluate(dataJson);
    },
    
    getBuild: function () {
        return this.build;
    },
    getCssJson: function () {
        return this.cssJson;
    },
    getData: function (urlDataAjax, section) {
	console.log("Getting Data: "+ urlDataAjax+" section:"+section);
        if (urlDataAjax != "") {
            this._setBuild(section);
           if (this.debug) console.log('Esta es la pagina que se va a cachear. Nuevo objeto PJSON()');
            this._preinit();
            this.setUrlGetData(urlDataAjax);
            this._callData(urlDataAjax);
            this.startTimeout();
           
        } else {
            this.errorMessage('03');
        }
    },
    getIdProcess: function () {
        return this.idProcess;
    },
    setIdProcess: function (s) {
        this.idProcess = s;
    },
    getDataFromAjax: function (section) {
        if (section != "") {
            this._setBuild(section);
            if (this.debug) console.log('Esta es la pagina que se va a cachear. Nuevo objeto PJSON()');
            this._preinit();
            this.stopLoad();
            this._responseCallData();
            this.startTimeout();
        } else {
            this.errorMessage('01');
        }
    },
    getResData: function () {
        return this.res_data;
    },
    getResStatus: function () {
        return this.res_status;
    },
    getResTextcodes: function () {
        return this.res_textcodes.code;
    },

    generateHtml: function (options) {
        var html = '';
        this._resetBuilt();
	if (this.debug) console.log("Generando html, targets a modificar:"+this.numTargets);
        if (this.numTargets > 0) {
		
            var options = Object.extend({
                pushData: this.pushBasic,
                mode: 'push'
            }, arguments[0] || {});
            this.vData.each(function (oData) {
                var target = oData.target;
                var html = oData.html;
		
                if (!html.empty()) {
                    this.setTarget(target);
		    if (this.debug) console.log("Target Actual:" + target);
                    var tpl = new Template(html);
                    this.setTpl(tpl);
		    
                    if (Object.isArray(oData.json)) {
                        vDataToPush = oData.json;
                    } else {
                        vDataToPush = [oData.json];
                    }
			//console.log("Datos a enviar"+ oData.json+ ":"+vDataToPush);
                    vDataToPush.each(options.pushData.bind(this));
                    this._pushBuilt(options.mode);
                    this._resetBuilt();
                }
                html = '';
            }, this);
        }
    },
    getBuilt: function () {
        return this.built;
    },
    getTarget: function () {
        return this.target;
    },
    getUrlGetData: function () {
        return this.url_getData;
    },
    parseResponse: function (response) {
        if (this.b_testResponse) {
            var Res = new Hash(response);
        } else {
            var Res = new Hash(response.responseText.evalJSON());
        }
        this.res_data = Res.get("data");
        this.res_status = Res.get("status");
        this.res_textcodes = Res.get("textcodes");
        this.res_webanalytics = Res.get("webanalytics");
    },
    pushBasic: function (dataJson) {
        this.addBuilt(dataJson);
    },
    reload: function () {
        if (this.reloadData) {
            var url = this.url_getData;
            this.numTargets = 0;
            this.reloading = true;
            this.getData(url, this.build);
        }
    },
    reset: function () {
        this.numTargets = 0;
        this.vData = [];
    },
    setCssJson: function (style) {
        this.cssJson = style;
    },
    setExtraInputs: function () {
        $$('.' + this.cssJson + '_radio').each(function (item) {
            var key = $(item).identify();
            var value = $F(item);
            if (value != '') {
                $(key + '_' + value).checked = true;
            }
        }, this);
        $$('.' + this.cssJson + '_select').each(function (item) {
            var key = $(item).identify();
            var value = $F(item);
            if (value != '') {
                if ($(key).title != '') {
                    if (key == 'member_birthday') {
                        valor = $(key).title;
                        if (valor.substring(0, 1) == '0') {
                            $(key).value = valor.substring(1);
                        } else {
                            $(key).value = $(key).title;
                        }
                    } else {
                        $(key).value = $(key).title;
                    }
                }
            }
        }, this);
    },
    setExtraImg: function () {
        $$('.' + this.cssJson + '_img').each(function (item) {
            pathImg = $(item).title;
            if (pathImg != '') {
                $(item).src = pathImg;
                $(item).title = '';
            }
        }, this);
    },
    setExtraLinks: function () {
        $$('.' + this.cssJson + '_link').each(function (item) {
            href = $(item).title;
            if (href != '') {
                $(item).href = href;
                $(item).title = '';
            }
        }, this);
    },
    setReload: function (reload) {
        this.reloadData = reload;
    },
    setReloading: function (reload) {
        this.reloading = reload;
    },
    setResData: function (data) {
        this.res_data = data;
    },
    setTarget: function (target) {
        this.target = target;
    },
    setTooltips: function (page) {},
    setTpl: function (tpl) {
        this.tpl = tpl;
    },
    setUrlGetData: function (url) {
        if (url != '') {
            this.url_getData = url;
        }
    },
    statusOK: function () {
        return (this.getResStatus() == "success");
    },
    testResponse: function (json) {
        this.test_response = json;
        this.b_testResponse = true;
    },
    _callData: function (urlDataAjax) {
	if(this.debug)console.log("Loading _callData():"+urlDataAjax);
        var params;
        if (urlDataAjax != '') {
            params = {
                onFailure: (function (response) {
                    if (this.debug) {}
                    this._showJson();
                    this.header(response.status);
                }).bind(this),
                onException: (function (response, error) {
                    if (this.debug) {
                        this.stopLoad();
                        this._showJson();
                            console.log('PrivaliaCoreJson.getData._callData.onException@' + this.getIdProcess() + ': ' + error);
                       
                    }
                }).bind(this),
                onComplete: this._responseCallData.bind(this)
            };
            new Ajax.Request(urlDataAjax, params);
        } else {
            this._init();
            this.errorMessage('04');
        }
    },
    _hideJson: function () {
        $$('.' + this.cssJson).each(function (item) {
            $(item.identify()).hide();
        });
    },
    _init: function () {
        if (this.debug) console.log('_init(): Iniciamos el volcado inteligente de datos');
        
            try {

                this.buildPage(this.getBuild());

            } catch (e) {
                
                    console.log(e, 'PrivaliaCoreJson.getData._init.buildPage@' + s_idProcess);
               
            }
        
        if (!this.error) {

            this.setTooltips(this.getBuild());
            this.setExtraInputs();
            this.setExtraImg();
            this.setExtraLinks();
            this.stopLoad();
            this._showJson();
            this.reloading = false;
        }
    },
    _preinit: function () {
        this.load();
	//alert(this.debug);
        if (this.debug) console.log('_preinit(): modo carga y tenemos previamente los bloques dinamicos ocultos');
    },
    _pushBuilt: function (s_mode) {
        var target = this.getTarget();
        var data = this.getBuilt();
	// if (this.debug)console.log("Target:"+target+"->"+data);
        if (data != '' && target != '') {
            switch (s_mode) {
            case 'add':
                $(target).insert({
                    bottom: data
                });
                break;
            case 'push':
            default:
                $(target).update(this.built);
            }
            this._setAsJsoned(target);
        }
    },
    _resetBuilt: function () {
        this.built = '';
        this.tpl = '';
    },
    _responseCallData: function (response) {
       
        this.stopTimeout();
        if (this.b_testResponse) {
            this.parseResponse(this.test_response);
        } else if (response !== undefined) {
            this.parseResponse(response);
        }
        if (this.isLogged()) {
            if (this.statusOK()) {
               
                    try {
                        this._setvData();
                    } catch (e) {
                       
                            console.log(e, 'PrivaliaCoreJson.getData._callData._responseCallData._setvData@' + s_idProcess);
                        
                    }
              
                console.log('getData(): obtenemos los datos via AJAX '+ response);
               
                    try {

                        this._init();

                    } catch (e) {
                        
                            console.log(e, 'PrivaliaCoreJson.getData._callData._responseCallData._init@' + s_idProcess);
                        
                    }
                
            } else {
                this.error = true;
                this.stopLoad();
                
            }
        } else {
            this.error = true;
            
        }
       
    },
    _set: function (target, json) {
        var html = '';
        if (target != "") {
            if (!this.reloading) {
                try {
			//alert(target);
                    html = $(target).innerHTML;
			//alert(html);
                } catch (e) {
                    if (this.debug) {
                        
                            console.log(e, 'PrivaliaCoreJson.getData._callData._responseCallData._set@[' + target + ']');
                        
                    }
                }
                this.vData[this.numTargets] = {
                    id: this.numTargets,
                    html: html,
                    json: json,
                    target: target
                };
            } else {
                if (this.vData.size() > 0) {
                    this.vData[this.numTargets].json = json;
                }
            }
            this.numTargets++;
        }
    },
    _setAsJsoned: function (target) {
        if (target != "") {
            $(target).removeClassName(this.cssJson);
            $(target).addClassName(this.cssJsoned);
        }
    },
    _setBuild: function (page) {
        if (page === undefined) {
            page = 'generic';
        }
        this.build = page;
    },
    _setvData: function () {
        if (!Object.isArray(this.getResData())) {
            var h = new Hash(this.getResData());
            h.each(function (item) {
                target = item[0];
                values = item[1];
                if (Object.isArray(values)) {
                    this._set(target, values);
                    if (values.size() === 0) {
                        this.showNoItems(target);
                    }
                } else {
                    this._set(target, values);
                    if (!values) {
                        if (this.debug) {
                            this.showNoItems(target);
                        } else {
                            try {
                                this.showNoItems(target);
                            } catch (e) {
                                if (typeof (DGuardian) != 'undefined') {
                                    DGuardian.log(e, 'PrivaliaCoreJson.getData._callData._responseCallData._servData@' + s_idProcess + '. No hay items. Intenta ocultar texto alternativo pero no existe ninguno');
                                }
                            }
                        }
                    }
                }
            }, this);
        }
    },
    _showJson: function () {
        $$('.' + this.cssJsoned).each(function (item) {
            new Effect.Appear(item, {
                duration: this.duration_show
            });
        }, this);
        $$('.' + this.cssJson).each(function (item) {
            $(item).update(' ');
            new Effect.Appear(item, {
                duration: this.duration_show
            });
        }, this);
    }
});

var PrivaliaCore = new Class.create(PrivaliaCoreJson, {
    initialize: function ($super) {
        $super();
        this.errId = '84';
        this.url_actual = '';
        this.url_logout = URL_DOMAIN + '/public/notlogged';
        this.version = 1.0;
        
    },
    
    getUrl: function () {
        var url;
        if (this.url_actual != '') {
            url = this.url_actual;
        } else {
            url = document.location.href;
            this.url_actual = url;
        }
        return url;
    },

    
    setAutocompleteOff: function (input) {
        $(input).setAttribute("autocomplete", "off");
    }
});

